package appapi.controller.oider;

import appapi.common.ResponseBean;
import appapi.entity.Zhongjiao.VersionEntity;
import appapi.service.VersionService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.net.InetAddress;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@RestController
@Api(value = "/GetServerSoftLastVersion", tags = "app升级")
@RequestMapping(value = "/api/update/GetServerSoftLastVersion")
public class AutomaticUpdateController {
    @Autowired
    private VersionService versionService;

    @PostMapping("/checkAppVersions")
    @ApiOperation(value = "文件上传接口，app版本更新")
    public ResponseBean checkAppVersion(@RequestParam("file") MultipartFile apkFile, String number) {
        if (apkFile.isEmpty()) {
            return ResponseBean.success("未选择文件");
        }
        try {
            // 通过Apache Commons FileUtils创建目标文件
            File targetDirectory = new File("/www/semp/images");
            File targetFile = new File(targetDirectory.getAbsolutePath(), apkFile.getOriginalFilename());
            /*
            删除目录下所有apk文件
             */
            File[] files = targetDirectory.listFiles();
            if (files != null) {
                for (File file : files) {
                    if (file.isFile() && file.getName().toLowerCase().endsWith(".apk")) {
                        file.delete();
                    }
                }
            }
            //将文件名获取到然后插入到数据库中
            VersionEntity versionEntity = new VersionEntity();
            versionEntity.setVersionName(apkFile.getOriginalFilename());
            versionEntity.setCreateTime(LocalDateTime.now());
            String originalFilename = apkFile.getOriginalFilename();
            String newFilename = originalFilename + "1.0";
            versionEntity.setVersionNumbser(number);
            versionService.insert(versionEntity);
            apkFile.transferTo(targetFile);
            return ResponseBean.success("文件上传成功");
        } catch (IOException e) {
            return ResponseBean.fail("文件上传失败: " + e.getMessage());
        }
    }

    @PostMapping("/checkJsonVersion")
    @ApiOperation(value = "配置文件上传接口")
    public ResponseBean checkJsonVersion(@RequestParam("file") MultipartFile apkFile) {
        if (apkFile.isEmpty()) {
            return ResponseBean.success("未选择文件");
        }
        try {
            // 通过Apache Commons FileUtils创建目标文件
            File targetDirectory = new File("/www/semp/images");
            File targetFile = new File(targetDirectory.getAbsolutePath(), apkFile.getOriginalFilename());
            /*
            删除目录下所有apk文件
             */
            File[] files = targetDirectory.listFiles();
            if (files != null) {
                for (File file : files) {
                    if (file.isFile() && file.getName().toLowerCase().endsWith(".json")) {
                        file.delete();
                    }
                }
            }
            //将文件名获取到然后插入到数据库中
            VersionEntity versionEntity = new VersionEntity();
            versionEntity.setVersionName(apkFile.getOriginalFilename());
            versionEntity.setCreateTime(LocalDateTime.now());
            String originalFilename = apkFile.getOriginalFilename();
            String newFilename = originalFilename + "1.0";
//            versionService.insert(versionEntity);
            apkFile.transferTo(targetFile);
            return ResponseBean.success("文件上传成功");
        } catch (IOException e) {
            return ResponseBean.fail("文件上传失败: " + e.getMessage());

        }
    }


    @GetMapping("/deleteFiles")
    @ApiOperation(value = "删除 JSON 和 APK 文件")
    public ResponseBean deleteJsonAndApkFiles() {
        try {
            String targetDirectoryPath = "/www/semp/images"; // 目标文件夹路径

            File targetDirectory = new File(targetDirectoryPath);
            File[] files = targetDirectory.listFiles();

            if (files != null) {
                for (File file : files) {
                    if (file.isFile() &&
                            (file.getName().toLowerCase().endsWith(".json") || file.getName().toLowerCase().endsWith(".apk"))) {
                        file.delete();
                    }
                }
            }

            return ResponseBean.success("JSON 和 APK 文件删除成功");
        } catch (Exception e) {
            return ResponseBean.fail("删除文件失败: " + e.getMessage());
        }
    }

    @GetMapping("/listApkFiles")
    @ApiOperation(value = "apk包下载地址")
    public ResponseBean listApkFiles(HttpServletRequest request) {
        try {
            // 获取服务器的IP地址
            String serverIp = InetAddress.getLocalHost().getHostAddress();

            String serverIps = "47.104.195.180:8080";
            // 设置目标目录
            File targetDirectory = new File("/www/semp/images");
            // 获取目标目录下的所有 APK 文件，并拼接服务器的IP地址
            List<String> apkFiles = new ArrayList<>();
            File[] files = targetDirectory.listFiles();
            if (files != null) {
                for (File file : files) {
                    if (file.isFile() && file.getName().toLowerCase().endsWith(".apk")) {
                        apkFiles.add("http://" + serverIps + "/images/" + file.getName());
                    }
                    if (file.isFile() && file.getName().toLowerCase().endsWith(".json")) {
                        String jsonContent = readJsonFile(file);
                        apkFiles.add(jsonContent);
                    }
                }
            }
            return ResponseBean.success(apkFiles);
        } catch (Exception e) {
            return ResponseBean.fail("查询失败: " + e.getMessage());
        }
    }
    @GetMapping("/listAll")
    @ApiOperation(value = "查询所有的版本信息")
    public ResponseBean<List<VersionEntity>> listAll(HttpServletRequest request) {
        List<VersionEntity> versionEntities = versionService.selectAll();
        if (versionEntities.size() == 0) {
            return ResponseBean.fail("您查询的信息为空");
        } else {
            return ResponseBean.success(versionEntities);
        }
    }


    private String readJsonFile(File file) {
        try {
            BufferedReader reader = new BufferedReader(new FileReader(file));
            StringBuilder stringBuilder = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                stringBuilder.append(line);
            }
            reader.close();
            return stringBuilder.toString();
        } catch (IOException e) {
            e.printStackTrace();
            return "";
        }
    }
}


